<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb
      separator="/"
      class="u-mb20"
    >
      <el-breadcrumb-item>
        <span
          class="c-text-high u-cursor"
          @click="back"
        >广告创意</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}广告创意</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 创建广告创意 -->
    <SectionContainer class="u-p30 u-mb30">
      <el-form
        ref="creativeForm"
        :model="creativeData"
        :rules="creativeRules"
        label-width="160px"
      >
        <!--投放信息-->
        <SectionTitle class="u-mb30">投放信息</SectionTitle>
        <div class="u-pb20">
          <el-form-item
            prop="planId"
            label="广告计划"
          >
            <el-select
              :disabled="['edit', 'detail'].indexOf(pageAction) !== -1"
              v-model="creativeData.planId"
              placeholder="请选择广告计划"
              filterable
              class="u-w450"
              @change="changePlanSelect"
            >
              <el-option
                v-for="item in planOptions"
                :key="item.planId"
                :label="item.planName"
                :value="item.planId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="unitId"
            label="广告单元"
          >
            <el-select
              :disabled="['edit', 'detail'].indexOf(pageAction) !== -1"
              v-model="creativeData.unitId"
              placeholder="请选择广告单元"
              filterable
              class="u-w450"
              @change="changeUnitSelect"
            >
              <el-option
                v-for="item in unitOptions"
                :key="item.unitId"
                :label="item.unitName"
                :value="item.unitId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="creativeName"
            label="创意名称"
          >
            <el-input
              :disabled="pageAction === 'detail'"
              v-model="creativeData.creativeName"
              placeholder="不可重复、不可包含特殊字符"
              class="u-w450"
            >
            </el-input>
            <ShowWordLimit
              :value="creativeData.creativeName"
              :maxlength="50"
            ></ShowWordLimit>
          </el-form-item>
        </div>

        <!--添加素材-->
        <SectionTitle class="u-pt30 u-mb30">添加素材
          <Tip inline>(此项仅创建创意的素材，投放媒体请在广告单元-投放媒体中选择)</Tip>
        </SectionTitle>
        <div class="u-pb20">
          <!--产品类型-->
          <el-form-item
            prop="creativeType"
            label="创意形式"
          >
            <el-radio-group
              :disabled="pageAction === 'detail'"
              v-model="creativeData.creativeType"
              @change="changeCreativeTemplate"
            >
              <el-radio
                v-for="item in GENERALIZE_CREATIVITY_TYPE"
                :label="item.value"
                :key="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>

          <!--创意模板-->
          <el-form-item
            v-if="creativeData.creativeType !== '' && creativeData.unitId !== ''"
            prop="creativeTemplateId"
            label="创意模板"
          >
            <el-radio-group
              :disabled="pageAction === 'detail'"
              v-model="creativeData.unionId"
              @change="changeCreativeAdx"
            >
              <el-radio
                class="u-lh40"
                v-for="item in adxOptions"
                :label="item.id"
                :key="item.id"
              >{{item.name}}</el-radio>
            </el-radio-group>
            <CustomContainer
              v-if="creativeData.unionId !== 0"
              style="width: 566px;"
            >
              <CreativeTemplate
                :disabled="pageAction === 'detail'"
                :data="creativeTemplateOptions"
                :template-id="creativeData.creativeTemplateId"
                @change="changeTemplate"
                @set-template="setTemplate"
              ></CreativeTemplate>
            </CustomContainer>
          </el-form-item>

          <template v-if="creativeData.creativeTemplateId !== 0">
            <!--创意素材（图片/视频）-->
            <el-form-item
              prop="materialPath"
              label="添加创意素材"
              style="width: 760px;"
            >
              <PreviewPicture
                :data="creativeFileList"
                :disabled="pageAction === 'detail'"
                @remove="creativeUploadRemove"
              ></PreviewPicture>
              <el-upload
                v-show="creativeFileList.length < creativeTemplate.imageNum"
                class="u-dib"
                ref="creativeUpload"
                list-type="picture-card"
                :disabled="pageAction === 'detail'"
                :action="`${UPLOAD_BASE_URL}/manage/api/bus/upload/uploadflie?fileGroups=1`"
                :headers="{'x-access-token': token}"
                :show-file-list="false"
                :before-upload="creativeUploadBefore"
                :on-success="creativeUploadSuccess"
                :on-progress="creativeUploadProgress"
                :on-error="creativeUploadError"
              >
                <el-progress
                  v-if="creativeFile.status === 'uploading'"
                  type="circle"
                  :stroke-width="6"
                  :percentage="creativeFile.percentage"
                >
                </el-progress>
                <i
                  v-else
                  class="el-icon-plus"
                ></i>
              </el-upload>
              <Tip v-if="pageAction !== 'detail'">请上传<b>{{creativeTemplate.imageNum}}</b>个{{creativeTemplate.imageWidth}}x{{creativeTemplate.imageHeight}}，<b class="c-text-high">{{creativeTemplate.imageFormat}}</b>格式的素材且不超过{{kb2mb(creativeTemplate.imageSize)}}</Tip>
            </el-form-item>

            <!--视频时长-->
            <el-form-item
              v-show="creativeTemplate.addVideoDuration === 0 && creativeData.videoDuration !== '' && creativeFileList.length > 0"
              prop="videoDuration"
              label="视频时长"
            >
              {{formatSeconds(creativeData.videoDuration)}}
            </el-form-item>

            <!--视频封面-->
            <el-form-item
              prop="coverPath"
              label="添加视频封面"
              v-show="creativeTemplate.addCoverPath === 0"
            >
              <PreviewPicture
                :data="coverFileList"
                :disabled="pageAction === 'detail'"
                @remove="coverUploadRemove"
              ></PreviewPicture>
              <el-upload
                v-show="coverFileList.length < 1"
                class="u-dib"
                ref="coverUpload"
                :disabled="pageAction === 'detail'"
                :action="`${UPLOAD_BASE_URL}/manage/api/bus/upload/uploadflie?fileGroups=1`"
                :headers="{'x-access-token': token}"
                list-type="picture-card"
                :show-file-list="false"
                :before-upload="coverUploadBefore"
                :on-success="coverUploadSuccess"
                :on-progress="coverUploadProgress"
                :on-error="coverUploadError"
              >
                <el-progress
                  v-if="coverFile.status === 'uploading'"
                  type="circle"
                  :stroke-width="6"
                  :percentage="coverFile.percentage"
                >
                </el-progress>
                <i
                  v-else
                  class="el-icon-plus"
                ></i>
              </el-upload>
              <Tip v-if="pageAction !== 'detail'">请上传<b>1</b>个{{creativeTemplate.coverWidth}}x{{creativeTemplate.coverHight}}，<b class="c-text-high">{{creativeTemplate.coverFormat}}</b>格式的文件且不超过{{kb2mb(creativeTemplate.coverSize)}}</Tip>
            </el-form-item>

            <!--标题文案-->
            <el-form-item
              prop="title"
              label="标题文案"
              v-show="creativeTemplate.addTitle === 0"
            >
              <el-input
                type="textarea"
                autosize
                :disabled="pageAction === 'detail'"
                v-model="creativeData.title"
                placeholder="请输入标题文案"
                class="u-w450"
              >
              </el-input>
              <ShowWordLimit
                :value="creativeData.title"
                :maxlength="creativeTemplate.titleWords"
              ></ShowWordLimit>
            </el-form-item>

            <!--描述-->
            <el-form-item
              prop="content"
              label="描述"
              v-show="creativeTemplate.addDescription === 0"
            >
              <el-input
                type="textarea"
                autosize
                :disabled="pageAction === 'detail'"
                v-model="creativeData.content"
                placeholder="请输入描述"
                class="u-w450"
              >
              </el-input>
              <ShowWordLimit
                :value="creativeData.content"
                :maxlength="creativeTemplate.descriptionWords"
              ></ShowWordLimit>
            </el-form-item>
          </template>
        </div>

        <template v-if="creativeData.creativeTemplateId !== 0">
          <!--投放链接-->
          <SectionTitle class="u-pt30 u-mb30">投放链接</SectionTitle>
          <div class="u-pb20">
            <!-- 链接类型 -->
            <el-form-item
              prop="systemDownload"
              label="链接类型"
            >
              <el-radio-group
                :disabled="pageAction === 'detail'"
                v-model="creativeData.systemDownload"
              >
                <el-radio
                  v-for="item in linkTypeOptions"
                  :label="item.value"
                  :key="item.value"
                >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <!--链接地址-->
            <el-form-item
              prop="targetUrl"
              label="链接地址"
            >
              <el-input
                type="textarea"
                autosize
                :disabled="pageAction === 'detail'"
                v-model="creativeData.targetUrl"
                placeholder="请输入链接地址"
                class="u-mr10 u-w450"
              >
              </el-input>
              <el-button
                @click="openWindow(creativeData.targetUrl)"
                type="primary"
              >点击预览</el-button>
            </el-form-item>
            <template v-if="[1, 2].includes(creativeData.systemDownload)">
              <!--bundleId-->
              <el-form-item
                prop="bundleId"
                label="bundleId"
                v-show="creativeData.systemDownload === 1"
              >
                <el-input
                  :disabled="pageAction === 'detail'"
                  v-model="creativeData.bundleId"
                  placeholder="请输入bundleId"
                  class="u-mr10 u-w450"
                >
                </el-input>
              </el-form-item>
              <!--应用名称-->
              <el-form-item>
                <span slot="label">应用名称</span>
                <el-input
                  :disabled="pageAction === 'detail'"
                  v-model="creativeData.applicationName"
                  placeholder="请输入应用名称"
                  class="u-mr10 u-w450"
                >
                </el-input>
              </el-form-item>
              <!--应用包名-->
              <el-form-item>
                <span slot="label">应用包名</span>
                <el-input
                  :disabled="pageAction === 'detail'"
                  v-model="creativeData.packageName"
                  placeholder="请输入应用包名"
                  class="u-mr10 u-w450"
                >
                </el-input>
              </el-form-item>
              <!--应用包大小-->
              <el-form-item>
                <span slot="label">应用包大小</span>
                <el-input
                  :disabled="pageAction === 'detail'"
                  v-model="creativeData.packageSize"
                  placeholder="请输入应用包大小"
                  class="u-mr10 u-w450"
                >
                </el-input>
                <el-select
                  class="u-w100"
                  v-model="creativeData.kbOrMb"
                  :disabled="pageAction === 'detail'"
                >
                  <el-option
                    label="KB"
                    value="1"
                  ></el-option>
                  <el-option
                    label="MB"
                    value="1024"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!--应用版本号-->
              <el-form-item>
                <span slot="label">应用版本号</span>
                <el-input
                  :disabled="pageAction === 'detail'"
                  v-model="creativeData.appVersion"
                  placeholder="请输入应用版本号"
                  class="u-mr10 u-w450"
                >
                </el-input>
              </el-form-item>
              <!--应用内部版本号-->
              <el-form-item>
                <span slot="label">应用内部版本号</span>
                <el-input
                  :disabled="pageAction === 'detail'"
                  v-model="creativeData.appVersionCode"
                  placeholder="请输入应用内部版本号"
                  class="u-mr10 u-w450"
                >
                </el-input>
              </el-form-item>
            </template>
            <!--deepLink-->
            <el-form-item>
              <span slot="label">deepLink</span>
              <el-input
                type="textarea"
                :disabled="pageAction === 'detail'"
                v-model="creativeData.deeplinkUrl"
                placeholder="请输入deepLink"
                class="u-mr10 u-w450"
              >
              </el-input>
            </el-form-item>
          </div>

          <!--产品信息-->
          <template v-if="creativeTemplate.addIcon === 0">
            <SectionTitle class="u-pt30 u-mb30">产品信息</SectionTitle>
            <!--产品名称-->
            <el-form-item
              prop="productName"
              label="产品名称"
            >
              <el-input
                :disabled="pageAction === 'detail'"
                v-model="creativeData.productName"
                placeholder="请输入产品名称"
                class="u-w450"
              >
              </el-input>
              <ShowWordLimit
                :value="creativeData.productName"
                :maxlength="creativeTemplate.iconWords"
              ></ShowWordLimit>
            </el-form-item>

            <!--产品图标-->
            <el-form-item
              prop="productLogoUrl"
              label="产品图标"
            >
              <PreviewPicture
                :data="productFileList"
                :disabled="pageAction === 'detail'"
                @remove="productUploadRemove"
              ></PreviewPicture>
              <el-upload
                v-show="productFileList.length < 1"
                class="u-dib"
                ref="productUpload"
                :disabled="pageAction === 'detail'"
                :action="`${UPLOAD_BASE_URL}/manage/api/bus/upload/uploadflie?fileGroups=3`"
                :headers="{'x-access-token': token}"
                list-type="picture-card"
                :show-file-list="false"
                :before-upload="productUploadBefore"
                :on-success="productUploadSuccess"
                :on-progress="productUploadProgress"
                :on-error="productUploadError"
              >
                <el-progress
                  v-if="productFile.status === 'uploading'"
                  type="circle"
                  :stroke-width="6"
                  :percentage="productFile.percentage"
                >
                </el-progress>
                <i
                  v-else
                  class="el-icon-plus"
                ></i>
              </el-upload>
              <Tip v-if="pageAction !== 'detail'">请上传<b>1</b>个{{creativeTemplate.iconWidth}}x{{creativeTemplate.iconHeight}}，<b class="c-text-high">{{creativeTemplate.iconFormat}}</b>格式的文件且不超过100KB</Tip>
            </el-form-item>
          </template>
        </template>
      </el-form>
    </SectionContainer>
    <div class="u-affix-bottom u-page-handle">
      <el-button
        size="small"
        @click="back"
      >返回</el-button>
      <el-button
        v-if="['create', 'copy'].indexOf(pageAction) !== -1"
        @click="performAction('create')"
        type="primary"
        size="small"
      >启用</el-button>
      <el-button
        v-if="pageAction === 'edit'"
        @click="performAction('save')"
        type="primary"
        size="small"
      >保存</el-button>
    </div>
    <!-- 保存确认 -->
    <DialogConfirm
      :visible.sync="saveOpenVisible"
      :buttons="['保 存', '取 消']"
      :button-primary="[0]"
      @confirm="confirmSaveOpen"
      content="保存将重新提交审核，是否保存？"
    ></DialogConfirm>
    <!-- 新建/复制确认 -->
    <DialogConfirm
      :visible.sync="addOpenVisible"
      :buttons="['启 用', '取 消']"
      :button-primary="[0]"
      @confirm="confirmAddOpen"
      content="启用将自动提交审核，是否启用？"
    ></DialogConfirm>
  </div>
</template>

<script>
import axios from "axios";
import { cloneDeep } from "lodash";

import DialogConfirm from "@/components/dialog-confirm";
import SectionContainer from "@/components/section-container";
import SectionTitle from "@/components/section-title";
import Tip from "@/components/tip";
import PreviewPicture from "@/components/preview-picture";
import ShowWordLimit from "@/components/show-word-limit";
import CustomContainer from "@/components/custom-container";
import CreativeTemplate from "./components/creative-template";

import {
  sessionStorage,
  getStrLen,
  isPicture,
  isVideo,
  formatSeconds,
  kb2mb
} from "@/utils";

import {
  GENERALIZE_CREATIVITY_TYPE,
  GENERALIZE_CREATIVITY_PLATFORM
} from "@/assets/js/common-option";

import {
  fetchPlanSelect,
  fetchUnitSelect,
  fetchAdxSelect,
  fetchCreativeTemplate,
  fetchCreativeAdd,
  fetchCreativeUpdate,
  fetchCreativeDetail,
  fetchAdLocalSelect
} from "@/api";

export default {
  components: {
    DialogConfirm,
    SectionContainer,
    SectionTitle,
    CreativeTemplate,
    CustomContainer,
    Tip,
    PreviewPicture,
    ShowWordLimit
  },
  data() {
    return {
      GENERALIZE_CREATIVITY_TYPE,
      GENERALIZE_CREATIVITY_PLATFORM,
      UPLOAD_BASE_URL: process.env.VUE_APP_UPLOAD_BASE_URL,
      user: sessionStorage.get("USER"),
      token: sessionStorage.get("USER").token,
      pageAction: this.$route.query.action,

      // 确认提交
      saveOpenVisible: false,
      addOpenVisible: false,

      planOptions: [],
      unitOptions: [],
      adxOptions: [],
      adxSourceOptions: [],
      creativeTemplateOptions: [],
      creativeTemplate: {},
      linkTypeOptions: [],
      adLocalOptions: [],

      // 创意数据
      creativeData: {
        planId: "", // 计划ID
        unitId: "", // 单元ID
        creativeName: "", // 创意名称
        creativeType: "", // 创意形式
        unionId: 0, // 创意模板adx
        creativeTemplateId: 0, // 创意模板
        materialPath: "", // 创意素材
        title: "", // 标题文案
        content: "", // 标题描述
        systemDownload: "", // 链接类型
        targetUrl: "", // 链接地址
        applicationName: "", // 应用名称
        packageName: "", // 应用包名
        packageSize: "", // 应用包大小
        kbOrMb: "1", // 应用包大小单位进制
        appVersion: "", // 应用版本号
        appVersionCode: "", // 应用内部版本号
        bundleId: "", // ios bundleId
        deeplinkUrl: "", // deeplink
        productName: "", // 产品名称
        productLogoUrl: "", // 产品图标
        coverPath: "", // 视频封面
        videoDuration: "", // 视频时长
        fileType: "", // 创意模板文件类型
        width: 0, // 创意模板文件尺寸
        height: 0, // 创意模板文件尺寸
        iconWidth: 0, // 产品icon尺寸
        iconHeight: 0, // 产品icon尺寸
        owner: sessionStorage.get("USER").userId // 用户ID
      },

      // 上传创意素材
      creativeFile: {},
      creativeFileList: [],
      // 上传视频封面
      coverFile: {},
      coverFileList: [],
      // 上传产品图标
      productFile: {},
      productFileList: [],

      creativeRules: {
        planId: {
          required: true,
          message: "请选择广告计划",
          trigger: ["blur", "change"]
        },
        unitId: {
          required: true,
          message: "请选择广告单元",
          trigger: ["blur", "change"]
        },
        creativeName: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入创意名称"));
            } else if (getStrLen(value) > 50) {
              callback(new Error("创意名称不能超过50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        creativeType: {
          required: true,
          message: "请选择创意形式",
          trigger: ["blur", "change"]
        },
        creativeTemplateId: {
          required: true,
          validator: (rule, value, callback) => {
            if (value === 0) {
              callback(new Error("请选择创意模板"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        materialPath: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请上传创意素材"));
            } else if (
              value.split(",").length !== this.creativeTemplate.imageNum
            ) {
              callback(
                new Error(`请上传${this.creativeTemplate.imageNum}个创意素材`)
              );
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        videoDuration: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.creativeTemplate.addVideoDuration === 0) {
              if (!value) {
                callback(new Error("视频时长不能为空"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        },
        coverPath: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.creativeTemplate.addCoverPath === 0) {
              if (!value) {
                callback(new Error("请上传视频封面"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        title: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.creativeTemplate.addTitle === 0) {
              if (!value || value.trim() === "") {
                callback(new Error("请输入标题文案"));
              } else if (getStrLen(value) > this.creativeTemplate.titleWords) {
                callback(
                  new Error(
                    `标题文案不能超过${this.creativeTemplate.titleWords}个字符`
                  )
                );
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        content: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.creativeTemplate.addDescription === 0) {
              if (!value || value.trim() === "") {
                callback(new Error("请输入描述"));
              } else if (
                getStrLen(value) > this.creativeTemplate.descriptionWords
              ) {
                callback(
                  new Error(
                    `描述不能超过${this.creativeTemplate.descriptionWords}个字符`
                  )
                );
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        systemDownload: {
          required: true,
          message: "请选择链接类型",
          trigger: ["blur", "change"]
        },
        targetUrl: {
          required: true,
          message: "请输入链接地址",
          trigger: ["blur", "change"]
        },
        bundleId: {
          required: true,
          validator: (rule, value, callback) => {
            if (
              this.creativeData.systemDownload === 1 &&
              (!value || value.trim() === "")
            ) {
              callback(new Error("请输入bundleId"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        productName: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.creativeTemplate.addIcon === 0) {
              if (!value || value.trim() === "") {
                callback(new Error("请输入产品名称"));
              } else if (getStrLen(value) > this.creativeTemplate.iconWords) {
                callback(
                  new Error(
                    `产品名称不能超过${this.creativeTemplate.iconWords}个字符`
                  )
                );
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        productLogoUrl: {
          required: true,
          validator: (rule, value, callback) => {
            if (this.creativeTemplate.addIcon === 0) {
              if (!value) {
                callback(new Error("请上传产品图标"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "创建",
        edit: "编辑",
        copy: "复制",
        detail: "查看"
      }[this.pageAction];
    }
  },
  methods: {
    formatSeconds,
    kb2mb,

    // 根据模板配置，清除不需要的值
    getCreativeData() {
      // 模块控制
      let {
        addCoverPath,
        addDescription,
        addIcon,
        addTitle,
        addVideoDuration
      } = this.creativeTemplate;
      // coverPath
      if (addCoverPath !== 0) {
        this.creativeData.coverPath = "";
      }
      // content
      if (addDescription !== 0) {
        this.creativeData.content = "";
      }
      // productName productLogoUrl
      if (addIcon !== 0) {
        this.creativeData.productName = "";
        this.creativeData.productLogoUrl = "";
      }
      // title
      if (addTitle !== 0) {
        this.creativeData.title = "";
      }
      // videoDuration
      if (addVideoDuration !== 0) {
        this.creativeData.videoDuration = "";
      }
      // 普通链接（0）：bundleId、applicationName、packageName、packageSize、appVersion、appVersionCode
      if (this.creativeData.systemDownload === 0) {
        this.creativeData.bundleId = "";
        this.creativeData.applicationName = "";
        this.creativeData.packageName = "";
        this.creativeData.packageSize = "";
        this.creativeData.appVersion = "";
        this.creativeData.appVersionCode = "";
      }
      // 安卓（2）：bundleId
      if (this.creativeData.systemDownload === 2) {
        this.creativeData.bundleId = "";
      }
      // 应用包大小转换
      if (this.creativeData.packageSize && this.creativeData.kbOrMb) {
        this.creativeData.packageSize = `${Math.ceil(
          this.creativeData.packageSize * this.creativeData.kbOrMb
        )}`;
      }
      return this.creativeData;
    },
    // 返回
    back() {
      this.$router.replace({
        name: this.$route.query.referrer,
        query: {
          ...this.$route.query.query
        }
      });
    },
    // 广告位
    fetchAdLocalSelect() {
      return fetchAdLocalSelect({
        query: Object.assign({
          unionId: 0,
          mediaId: 0,
          adspaceType: 0
        })
      }).then(res => {
        this.adLocalOptions = res.data.list;
      });
    },
    // 广告计划
    fetchPlanSelect() {
      return fetchPlanSelect({
        query: {
          userId: this.user.userId
        }
      }).then(res => {
        this.planOptions = res.data;
        if (this.$route.query.planId) {
          this.creativeData.planId = Number(this.$route.query.planId);
        }
      });
    },
    // 广告单元
    fetchUnitSelect() {
      return fetchUnitSelect({
        query: {
          userId: this.user.userId,
          planId: this.creativeData.planId || Number(this.$route.query.planId) || 0
        }
      }).then(res => {
        this.unitOptions = res.data;
        if (this.$route.query.unitId) {
          this.creativeData.unitId = Number(this.$route.query.unitId);
        }
      });
    },
    // adx
    fetchAdxSelect() {
      return fetchAdxSelect({
        query: {
          unionId: 0 // adx，默认
        }
      }).then(res => {
        this.adxSourceOptions = res.data.list;
      });
    },
    // 链接类型选项，根据模板配置
    getLinkTypeOptions(type) {
      let types = type.split(",").map(item => Number(item));
      return GENERALIZE_CREATIVITY_PLATFORM.filter(item => {
        return types.includes(item.value);
      });
    },
    // 创意模板
    fetchCreativeTemplate() {
      return fetchCreativeTemplate({
        query: {
          unionId: this.creativeData.unionId,
          templateType: this.creativeData.creativeType
        }
      }).then(res => {
        this.creativeTemplateOptions = this.filterCreativeTemplate(
          res.data.list
        );
      });
    },
    // 选中单元数据
    filterUnitOption() {
      let ret = {
        spaceAdx: [],
        unitMedia: {},
        selectTemplate: {},
        allTemplate: {}
      };
      if (!this.creativeData.unitId) return ret;
      // 选中的单元
      ret.unitMedia = this.unitOptions.find(
        unit => unit.unitId === this.creativeData.unitId
      );
      // 单元选择的广告位
      let unitMediaValue = ret.unitMedia.mediaValue.split(",");
      // 广告位对应图片模板
      this.adLocalOptions.forEach(adx => {
        ret.selectTemplate[adx.id] = {};
        ret.allTemplate[adx.id] = {};
        adx.children.forEach(media => {
          media.children.forEach(space => {
            if (space.adspaceSize && unitMediaValue.includes(space.id)) {
              space.adspaceSize.split(",").forEach(key => {
                ret.selectTemplate[adx.id][key] =
                  ret.selectTemplate[adx.id][key] || [];
                ret.selectTemplate[adx.id][key].push(space.name);
              });
            }
            space.adspaceSize.split(",").forEach(key => {
              ret.allTemplate[adx.id][key] = ret.allTemplate[adx.id][key] || [];
              ret.allTemplate[adx.id][key].push(space.name);
            });
          });
        });
      });
      // 选中广告位来自哪些adx
      for (let key in ret.selectTemplate) {
        if (Object.keys(ret.selectTemplate[key]).length) {
          ret.spaceAdx.push(key);
        }
      }
      return ret;
    },
    // 过滤创意模板
    filterCreativeTemplate(data) {
      let { unitMedia, selectTemplate, allTemplate } = this.filterUnitOption();
      // 投放媒体不限
      if (!unitMedia.mediaChoice) {
        data.forEach(item => {
          let rect = `${item.imageWidth}x${item.imageHeight}`;
          item.applyAdspace =
            allTemplate[this.creativeData.unionId][rect] || [];
        });
        return data;
      }
      // 自定义媒体
      let adxTemplate = selectTemplate[this.creativeData.unionId];
      let adxTemplateRect = Object.keys(adxTemplate);
      return data.filter(item => {
        let rect = `${item.imageWidth}x${item.imageHeight}`;
        item.applyAdspace = adxTemplate[rect] || [];
        return adxTemplateRect.includes(rect);
      });
    },
    // 改变创意形式
    changeCreativeTemplate() {
      this.clearCreativeTemplate();
      this.creativeData.unionId = 0;
      this.creativeTemplateOptions = [];
      this.creativeData.creativeTemplateId = 0;
      this.$refs.creativeForm.validateField("creativeTemplateId");
    },
    // 改变创意adx
    changeCreativeAdx() {
      this.clearCreativeTemplate();
      this.creativeTemplateOptions = [];
      this.creativeData.creativeTemplateId = 0;
      this.$refs.creativeForm.validateField("creativeTemplateId");
      this.fetchCreativeTemplate();
    },
    // 改变模板
    changeTemplate(template) {
      this.clearCreativeTemplate();
      this.setTemplate(template);
      if (this.$refs.creativeUpload) {
        this.$refs.creativeUpload.clearFiles();
      }
      this.$refs.creativeForm.clearValidate();
      this.creativeData.systemDownload = +template.linkType.split(",")[0];
    },
    // 设置模板
    setTemplate(template) {
      this.creativeData.width = template.imageWidth;
      this.creativeData.height = template.imageHeight;
      this.creativeData.iconWidth = template.iconWidth;
      this.creativeData.iconHeight = template.iconHeight;
      this.creativeTemplate = template;
      this.linkTypeOptions = this.getLinkTypeOptions(template.linkType);
      this.creativeData.creativeTemplateId = template.templateId;
      this.$refs.creativeForm.validateField("creativeTemplateId");
    },
    // 清空创意模板
    clearCreativeTemplate() {
      this.creativeTemplate = {};
      // 创意素材
      this.creativeFileList = [];
      this.creativeFile = {};
      this.creativeData.materialPath = "";
      this.creativeData.fileType = "";
      // 视频封面
      this.coverFileList = [];
      this.coverFile = {};
      this.creativeData.coverPath = "";
      // 产品图标
      this.productFileList = [];
      this.productFile = {};
      this.creativeData.productLogoUrl = "";
    },
    // 广告计划改变
    changePlanSelect() {
      this.creativeData.unitId = "";
      this.fetchUnitSelect();
    },
    // 过滤adx
    filterSpaceAdx() {
      let { unitMedia, spaceAdx } = this.filterUnitOption();
      if (unitMedia.mediaChoice) {
        this.adxOptions = this.adxSourceOptions.filter(item =>
          spaceAdx.includes(String(item.id))
        );
      } else {
        this.adxOptions = cloneDeep(this.adxSourceOptions);
      }
    },
    // 广告单元改变
    changeUnitSelect() {
      this.filterSpaceAdx();
      this.changeCreativeTemplate();
    },
    // 上传文件格式
    // @params {string} templateType只能包含 "png,jpg,gif,mp4"
    isUploadFormat(templateType, name) {
      let types = templateType.split(",");
      return types.some(item => {
        return name.endsWith(item);
      });
    },
    // 更新创意提交的参数
    updateCreativeFileList() {
      this.creativeData.materialPath = this.creativeFileList
        .map(item => item.url)
        .join();
      this.creativeData.fileType = this.creativeFileList
        .map(item => item.type)
        .join();
      this.$refs.creativeForm.validateField("materialPath");
    },
    // 中断上传
    uploadAbort(ref, file) {
      this.$refs[ref].abort(file);
    },
    // 创意素材验证
    creativeUploadBefore(file) {
      const type = this.isUploadFormat(
        this.creativeTemplate.imageFormat,
        file.name
      );
      const size = file.size / 1024 < this.creativeTemplate.imageSize;
      if (isPicture(file.name)) {
        this.getUploadImage(file).then(({ width, height }) => {
          // 类型
          if (!type) {
            this.$message.error(
              `请上传${this.creativeTemplate.imageFormat}格式的创意素材`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          // 个数
          if (this.creativeFileList.length === this.creativeTemplate.imageNum) {
            this.$message.error(
              `创意素材限制上传${this.creativeTemplate.imageNum}个文件`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          // 尺寸
          if (
            this.creativeTemplate.imageWidth !== width ||
            this.creativeTemplate.imageHeight !== height
          ) {
            this.$message.error(
              `创意素材尺寸要求${this.creativeTemplate.imageWidth}x${this.creativeTemplate.imageHeight}`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          // 大小
          if (!size) {
            this.$message.error(
              `创意素材大小不能超过${kb2mb(this.creativeTemplate.imageSize)}`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          return true;
        });
      } else if (isVideo(file.name)) {
        this.getUploadVideo(file).then(({ width, height, duration }) => {
          // 类型
          if (!type) {
            this.$message.error(
              `请上传${this.creativeTemplate.imageFormat}格式的创意素材`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          // 个数
          if (this.creativeFileList.length >= this.creativeTemplate.imageNum) {
            this.$message.error(
              `创意视频限制上传${this.creativeTemplate.imageNum}个文件`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          // 尺寸
          if (
            this.creativeTemplate.imageWidth !== width ||
            this.creativeTemplate.imageHeight !== height
          ) {
            this.$message.error(
              `创意视频尺寸要求${this.creativeTemplate.imageWidth}x${this.creativeTemplate.imageHeight}`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          // 时长
          let durationMin = this.creativeTemplate.videoDuration.split("-")[0],
            durationMax = this.creativeTemplate.videoDuration.split("-")[1];
          if (duration < durationMin || duration > durationMax) {
            this.$message.error(
              `创意视频时长要求${this.creativeTemplate.videoDuration}秒`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          // 大小
          if (!size) {
            this.$message.error(
              `创意视频大小不能超过${kb2mb(this.creativeTemplate.imageSize)}`
            );
            this.uploadAbort("creativeUpload", file);
            return false;
          }
          this.creativeData.videoDuration = duration;
          return true;
        });
      } else {
        this.$message.error("请上传正确格式的文件");
        this.uploadAbort("creativeUpload", file);
        return false;
      }
    },
    // 创意上传成功
    creativeUploadSuccess(res, file) {
      this.creativeFile = file;
      this.creativeFileList.push({
        name: this.getUploadFileName(file.response.data.uploadUrl),
        type: file.raw.type,
        url: file.response.data.uploadUrl
      });
      this.updateCreativeFileList();
    },
    // 创意上传进度
    creativeUploadProgress(event, file) {
      let percentage = parseInt(file.percentage, 10);
      this.creativeFile = {
        ...file,
        percentage: percentage === 100 ? 99 : percentage
      };
    },
    // 创意上传失败
    creativeUploadError(err, file) {
      this.creativeFile = file;
    },
    // 创意删除
    creativeUploadRemove({ url }) {
      this.creativeFileList = this.creativeFileList.filter(
        item => item.url !== url
      );
      this.updateCreativeFileList();
    },
    // 产品格式验证
    productUploadBefore(file) {
      const type = this.isUploadFormat(
        this.creativeTemplate.iconFormat,
        file.name
      );
      const size = file.size / 1024 < 100;
      if (isPicture(file.name)) {
        this.getUploadImage(file).then(({ width, height }) => {
          // 类型
          if (!type) {
            this.$message.error(
              `请上传${this.creativeTemplate.iconFormat}格式的文件`
            );
            this.uploadAbort("productUpload", file);
            return false;
          }
          // 个数
          if (this.productFileList.length >= 1) {
            this.$message.error("文件限制上传1个");
            this.uploadAbort("productUpload", file);
            return false;
          }
          // 尺寸
          if (
            this.creativeTemplate.iconWidth !== width ||
            this.creativeTemplate.iconHeight !== height
          ) {
            this.$message.error(
              `文件尺寸要求${this.creativeTemplate.iconWidth}x${this.creativeTemplate.iconHeight}`
            );
            this.uploadAbort("productUpload", file);
            return false;
          }
          // 大小
          if (!size) {
            this.$message.error(`文件大小不能超过100KB`);
            this.uploadAbort("productUpload", file);
            return false;
          }
          return true;
        });
      } else {
        this.$message.error(
          `请上传${this.creativeTemplate.iconFormat}格式的文件`
        );
        this.uploadAbort("productUpload", file);
        return false;
      }
    },
    // 产品上传成功
    productUploadSuccess(res, file) {
      this.productFile = file;
      this.productFileList = [
        {
          name: this.getUploadFileName(res.data.uploadUrl),
          url: res.data.uploadUrl
        }
      ];
      this.creativeData.productLogoUrl = res.data.uploadUrl;
      this.$refs.creativeForm.validateField("productLogoUrl");
    },
    // 创意上传进度
    productUploadProgress(event, file) {
      let percentage = parseInt(file.percentage, 10);
      this.productFile = {
        ...file,
        percentage: percentage === 100 ? 99 : percentage
      };
    },
    // 创意上传失败
    productUploadError(err, file) {
      this.productFile = file;
    },
    // 产品删除
    productUploadRemove() {
      this.productFileList = [];
      this.creativeData.productLogoUrl = "";
      this.$refs.creativeForm.validateField("productLogoUrl");
    },
    // 封面格式验证
    coverUploadBefore(file) {
      const type = this.isUploadFormat(
        this.creativeTemplate.coverFormat,
        file.name
      );
      const size = file.size / 1024 < this.creativeTemplate.coverSize;
      if (isPicture(file.name)) {
        this.getUploadImage(file).then(({ width, height }) => {
          // 类型
          if (!type) {
            this.$message.error(
              `请上传${this.creativeTemplate.coverFormat}格式的文件`
            );
            this.uploadAbort("coverUpload", file);
            return false;
          }
          // 个数
          if (this.coverFileList.length >= 1) {
            this.$message.error("文件限制上传1个");
            this.uploadAbort("coverUpload", file);
            return false;
          }
          // 尺寸
          if (
            this.creativeTemplate.coverWidth !== width ||
            this.creativeTemplate.coverHight !== height
          ) {
            this.$message.error(
              `文件尺寸要求${this.creativeTemplate.coverWidth}x${this.creativeTemplate.coverHight}`
            );
            this.uploadAbort("coverUpload", file);
            return false;
          }
          // 大小
          if (!size) {
            this.$message.error(`文件大小不能超过100KB`);
            this.uploadAbort("coverUpload", file);
            return false;
          }
          return true;
        });
      } else {
        this.$message.error(
          `请上传${this.creativeTemplate.coverFormat}格式的文件`
        );
        this.uploadAbort("coverUpload", file);
        return false;
      }
    },
    // 封面上传成功
    coverUploadSuccess(res, file) {
      this.coverFile = file;
      this.coverFileList = [
        {
          name: this.getUploadFileName(res.data.uploadUrl),
          url: res.data.uploadUrl
        }
      ];
      this.creativeData.coverPath = res.data.uploadUrl;
      this.$refs.creativeForm.validateField("coverPath");
    },
    // 封面上传进度
    coverUploadProgress(event, file) {
      let percentage = parseInt(file.percentage, 10);
      this.coverFile = {
        ...file,
        percentage: percentage === 100 ? 99 : percentage
      };
    },
    // 封面上传失败
    coverUploadError(err, file) {
      this.coverFile = file;
    },
    // 封面删除
    coverUploadRemove() {
      this.coverFileList = [];
      this.creativeData.coverPath = "";
      this.$refs.creativeForm.validateField("coverPath");
    },
    // 获取图片文件
    getUploadImage(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          const image = new Image();
          image.onload = () => {
            resolve({
              image,
              width: image.width,
              height: image.height
            });
          };
          image.onerror = () => {
            reject({
              image: null,
              width: 0,
              height: 0
            });
          };
          image.src = reader.result;
        };
        reader.readAsDataURL(file);
      });
    },
    // 获取视频文件
    getUploadVideo(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          const video = document.createElement("video");
          video.onloadedmetadata = () => {
            resolve({
              video,
              height: video.videoHeight,
              width: video.videoWidth,
              duration: video.duration
            });
          };
          video.onerror = () => {
            reject({
              video: null,
              width: 0,
              height: 0,
              duration: 0
            });
          };
          video.src = reader.result;
        };
        reader.readAsDataURL(file);
      });
    },
    // 截取上传文件名称
    getUploadFileName(url) {
      return url.match(/[^/]+$/g)[0];
    },
    // 详情
    fetchCreativeDetail() {
      fetchCreativeDetail({
        query: {
          id: this.$route.query.creativeId
        }
      }).then(res => {
        let {
          id,
          planId,
          unitId,
          creativeName,
          creativeType,
          unionId,
          creativeTemplateId,
          materialPath,
          title,
          content,
          systemDownload,
          targetUrl,
          applicationName,
          packageName,
          packageSize,
          kbOrMb,
          appVersion,
          appVersionCode,
          productName,
          productLogoUrl,
          fileType,
          width,
          height,
          owner,
          bundleId,
          deeplinkUrl,
          coverPath,
          videoDuration
        } = res.data;
        // 创意数据回显
        this.creativeData = {
          planId,
          unitId,
          creativeName,
          creativeType,
          unionId,
          creativeTemplateId,
          materialPath,
          title,
          content,
          systemDownload,
          targetUrl,
          applicationName,
          packageName,
          packageSize,
          appVersion,
          appVersionCode,
          productName,
          productLogoUrl,
          fileType,
          width,
          height,
          owner,
          bundleId,
          deeplinkUrl,
          coverPath,
          videoDuration,
          kbOrMb: kbOrMb || "1"
        };
        // 编辑需要原id
        if ("edit" === this.pageAction) {
          this.creativeData.id = id;
        }
        // 应用包大小
        if (packageSize) {
          this.creativeData.packageSize = `${Math.ceil(packageSize / kbOrMb)}`;
        }
        // 创意素材回显
        this.creativeFileList = this.getCreativeFileList(
          materialPath,
          fileType
        );
        // 视频封面，只有一个
        this.coverFileList = [];
        if (coverPath) {
          this.coverFileList = [
            {
              name: this.getUploadFileName(coverPath),
              url: coverPath
            }
          ];
        }
        // 产品图标回显，只有一个
        this.productFileList = [];
        if (productLogoUrl) {
          this.productFileList = [
            {
              name: this.getUploadFileName(productLogoUrl),
              url: productLogoUrl
            }
          ];
        }
        // 过滤adx
        this.filterSpaceAdx();
        // 初始化模板
        this.fetchCreativeTemplate();
      });
    },
    // 创意素材模板默认
    getCreativeFileList(url, type) {
      if (!url) return [];
      let types = type.split(",");
      let urls = url.split(",");
      let ret = [];
      types.forEach((item, index) => {
        ret.push({
          name: this.getUploadFileName(urls[index]),
          type: item,
          url: urls[index]
        });
      });
      return ret;
    },
    // 新建、编辑、复制
    initDetail() {
      // 新建
      if (this.pageAction === "create") {
        this.changeUnitSelect();
      }
      // 除新建外需要请求已有数据
      else {
        this.fetchCreativeDetail();
      }
    },
    // 新建
    addItem() {
      return fetchCreativeAdd({
        query: {
          userId: this.user.userId
        },
        body: this.getCreativeData()
      }).then(res => {
        this.$message({
          message: "操作成功",
          duration: 1000
        });
        return res;
      });
    },
    addItemSave() {
      this.addItem().then(res => {
        this.addOpenVisible = false;
        setTimeout(() => {
          let { planId, unitId } = res.data;
          this.$router.replace({
            name: "generalize-creative",
            query: {
              planId,
              unitId
            }
          });
        }, 1000);
      });
    },
    addItemOpenSave() {
      this.$refs["creativeForm"].validate((valid, params) => {
        if (valid) {
          this.addOpenVisible = true;
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    // 更新
    updateItem() {
      return fetchCreativeUpdate({
        body: this.getCreativeData()
      }).then(res => {
        this.$message({
          message: "操作成功",
          duration: 1000
        });
        return res;
      });
    },
    updateItemSave() {
      this.updateItem().then(() => {
        this.saveOpenVisible = false;
        setTimeout(() => {
          this.back();
        }, 1000);
      });
    },
    updateItemOpenSave() {
      this.$refs["creativeForm"].validate((valid, params) => {
        if (valid) {
          this.saveOpenVisible = true;
        } else {
          this.$message({
            type: "error",
            message: params[Object.keys(params)[0]][0].message,
            duration: 1000
          });
        }
      });
    },
    // 启用、确定
    performAction(type) {
      // 启用
      if ("create" === type) {
        this.addItemOpenSave();
      }
      // 保存
      else if ("save" === type) {
        this.updateItemOpenSave();
      }
    },
    // 打开新页面
    openWindow(url) {
      if (url) {
        window.open(url);
      }
    },
    // 保存确认提交
    confirmSaveOpen(index) {
      if (index === 0) {
        this.updateItemSave();
      } else {
        this.saveOpenVisible = false;
      }
    },
    // 新建、复制确认提交
    confirmAddOpen(index) {
      if (index === 0) {
        this.addItemSave();
      } else {
        this.addOpenVisible = false;
      }
    }
  },
  created() {
    axios
      .all([
        this.fetchPlanSelect(),
        this.fetchUnitSelect(),
        this.fetchAdxSelect(),
        this.fetchAdLocalSelect()
      ])
      .then(
        axios.spread(() => {
          this.initDetail();
        })
      );
  }
};
</script>
